package net.xdclass.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.ClientTypeEnum;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.request.ConfirmOrderRequest;
import net.xdclass.request.RepayOrderRequest;
import net.xdclass.service.ProductOrderService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 孙浩
 * @since 2022-05-11
 */
@Api("订单模块")
@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {

  @Autowired
  private ProductOrderService orderService;

  @Autowired
  private StringRedisTemplate stringRedisTemplate;


  @ApiOperation("获取订单token")
  @GetMapping("/get_token")
  public JsonData getOrderToken() {
    LoginUser loginUser = LoginInterceptor.threadLocal.get();
    String orderKey = String.format(CacheKey.SUBMIT_ORDER_TOKEN_KEY, loginUser.getId());
    String token = CommonUtil.getStringNumRandom(32);
    stringRedisTemplate.opsForValue().set(orderKey, token, 30, TimeUnit.MINUTES);
    return JsonData.buildSuccess(token);
  }

  @ApiOperation("提交订单")
  @PostMapping("confirm")
  public void confirmOrder(@ApiParam("订单对象") @RequestBody ConfirmOrderRequest orderRequest, HttpServletResponse response) {
    JsonData jsonData = orderService.confirmOrder(orderRequest);
    handleRearData(jsonData, orderRequest.getClientType(), orderRequest.getPayType(), response);
  }

  /**
   * 查询订单状态
   */
  @ApiOperation("查询订单状态")
  @GetMapping("/query_product_order_state/{outTradeNo}")
  public JsonData queryProductOrderState(@ApiParam(value = "订单号", required = true) @PathVariable(value = "outTradeNo") String outTradeNo) {
    return orderService.queryProductOrderState(outTradeNo);
  }

  /**
   * 订单分页列表
   */
  @ApiOperation("订单分页列表")
  @GetMapping("/page")
  public JsonData page(@ApiParam(value = "页数", defaultValue = "1")
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @ApiParam(value = "条数", defaultValue = "10")
                       @RequestParam(value = "size", defaultValue = "10") Integer size, @RequestParam(value = "state", required = false) String state) {
    return JsonData.buildSuccess(orderService.pageOrder(page, size, state));
  }


  /**
   * 重新发起支付
   */
  @ApiOperation("重新发起支付")
  @PostMapping("/repay")
  public void repayOrder(@ApiParam(value = "订单对象") @RequestBody RepayOrderRequest repayOrderRequest, HttpServletResponse response) {
    JsonData jsonData = orderService.repayOrder(repayOrderRequest);
    handleRearData(jsonData, repayOrderRequest.getClientType(), repayOrderRequest.getPayType(), response);
  }

  private void handleRearData(JsonData jsonData, String client, String payType, HttpServletResponse response) {
    if (jsonData.getCode() == 0) {
      //如果是支付宝网页支付，都是跳转网页，APP除外
      if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
        log.info("创建支付宝订单成功");
        if (client.equalsIgnoreCase(ClientTypeEnum.H5.name())) {
          CommonUtil.writeData(response, jsonData);
        } else if (client.equalsIgnoreCase(ClientTypeEnum.APP.name())) {
          //APP SDK支付  TODO
        }
      } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT.name())) {
        //微信支付 TODO
      }
    } else {
      log.error("创建订单失败{}", jsonData);
    }
  }
}

